<?php


namespace app\auth\controller;


use app\api\model\User;
use app\framework\BaseController;
use app\framework\Http;
use app\framework\IConstants;
use app\framework\Utils;
use think\Exception;

class Login extends BaseController
{
    /**
     * 小程序用户登录凭证校验
     * @param $code 登录时获取的code
     */
    public function check($code = null){
        try{
            if(empty($code)){
                throw new Exception(BaseController::MSG_JS_CODE_NOT_BLANK);
            }
            $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='
                .IConstants::APP_ID
                .'&secret='
                .IConstants::SECRET
                .'&js_code='
                .$code
                .'&grant_type=authorization_code';
            $res = Http::curl_request($url);
            $data = json_decode($res,true);
            if(empty($data['openid'])){
                if(empty($data['errmsg'])){
                    throw new Exception(BaseController::MSG_FAIL_CONNECT_WX_SERVER);
                }
                throw new Exception($data['errmsg']);
            }

            // 入库
            $tmp = User::get(['open_id' => $data['openid']]);
            if(empty($tmp)){
                $user = new User();
                $user->id = Utils::create_guid();
                $user->open_id = $data['openid'];
                $user->create_time = date('Y-m-d h:i:s', time());
                $user->save();
            }
            $token = Utils::authCode($data['openid'],false);
            self::writeJSON($token,BaseController::MSG_OK,BaseController::SC_OK);
        }catch (\Exception $e){
            self::writeJSON(null,$e->getMessage(),self::SC_FAIL);
        }
    }
}